"""统一异常处理模块"""

from fastapi import Request, status
from fastapi.responses import JSONResponse
from .logger import get_logger

logger = get_logger(__name__)

class FinSentiException(Exception):
    """金融情感分析平台基础异常类"""
    error_code = "FIN_SENTI_ERROR"
    status_code = 500

    def __init__(self, message, error_code=None, status_code=None):
        super().__init__(message)
        self.message = message
        if error_code:
            self.error_code = error_code
        if status_code:
            self.status_code = status_code

class ModelException(FinSentiException):
    """模型相关异常"""
    error_code = "MODEL_ERROR"
    status_code = 503

class DataException(FinSentiException):
    """数据相关异常"""
    error_code = "DATA_ERROR"
    status_code = 400

class SecurityException(FinSentiException):
    """安全相关异常"""
    error_code = "SECURITY_ERROR"
    status_code = 401

class PermissionDeniedException(SecurityException):
    """权限拒绝异常"""
    error_code = "PERMISSION_DENIED"
    status_code = 403

# 注意：全局异常处理器应在main.py中注册，而不是在这里直接定义
# 以下代码作为示例，实际应在FastAPI应用实例化的地方添加
# def register_exception_handlers(app):
#     """注册全局异常处理器"""
#     @app.exception_handler(FinSentiException)
#     async def fin_senti_exception_handler(request: Request, exc: FinSentiException):
#         logger.error(f"{exc.error_code}: {exc.message}")
#         return JSONResponse(
#             status_code=exc.status_code,
#             content={
#                 "error_code": exc.error_code,
#                 "message": exc.message
#             }
#         )